#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
import os, re, sys, tempfile

ENV_DIR = Path.home() / ".config" / "environment.d"
ENV_FILE = ENV_DIR / "fcitx.conf"
LINE = "XMODIFIERS=@im=fcitx"

def ensure_dir():
    ENV_DIR.mkdir(parents=True, exist_ok=True)

def read_file(path: Path) -> str:
    return path.read_text(encoding="utf-8", errors="ignore") if path.exists() else ""

def atomic_write(path: Path, content: str):
    fd, tmp = tempfile.mkstemp(prefix=".envd.", dir=str(path.parent))
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(content)
        f.flush()
        os.fsync(f.fileno())
    os.replace(tmp, path)

def normalize(text: str) -> str:
    out = []
    pat = re.compile(r"^\s*XMODIFIERS\s*=", re.I)
    for raw in text.splitlines():
        if pat.match(raw) and not raw.strip().startswith("#"):
            continue
        out.append(raw)
    if LINE not in out:
        out.append(LINE)
    return "\n".join([l for l in out if l.strip()]) + "\n"

def main():
    ensure_dir()
    before = read_file(ENV_FILE)
    after = normalize(before)
    if after != before:
        atomic_write(ENV_FILE, after)
        print(f"已写入 {ENV_FILE}: {LINE}")
    else:
        print("无需修改：配置已是目标状态。")

if __name__ == "__main__":
    sys.exit(main() or 0)
